package com.link.ppt.View;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.link.ppt.App.App;
import com.link.ppt.Base.BaseActivity;
import com.link.ppt.Consts.Constants;
import com.link.ppt.Model.Bean.BaseBean;
import com.link.ppt.Model.Bean.PPTDetailBean;
import com.link.ppt.Model.Bean.PPTEntity;
import com.link.ppt.Model.Bean.ScorePPT;
import com.link.ppt.Model.IPPTModel;
import com.link.ppt.Model.Impl.PPTModelImpl;
import com.link.ppt.R;
import com.link.ppt.Utils.CommonSubscriber;
import com.link.ppt.Utils.DisplayUtil;
import com.link.ppt.Utils.FileUtils;
import com.link.ppt.Utils.GlideUtils;
import com.link.ppt.Utils.PreferenceUtils;
import com.link.ppt.Utils.TimeUtils;
import com.link.ppt.Utils.ToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.functions.Action0;

/**
 * Created by liucxu on 2018/1/30.
 */

public class PPTWebviewActivity extends BaseActivity {


    private String pptId;
    private PPTEntity entity;

    @BindView(R.id.scrollWebview)
    WebView scrollWebview;
    @BindView(R.id.tv_ppt_name)
    TextView tv_ppt_name;

    @BindView(R.id.tv_ppt_author)
    TextView tv_ppt_author;
    @BindView(R.id.right_layout)
    LinearLayout right_layout;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.imv_1star)
    ImageView imv_1star;
    @BindView(R.id.imv_2star)
    ImageView imv_2star;
    @BindView(R.id.imv_3star)
    ImageView imv_3star;
    @BindView(R.id.imv_4star)
    ImageView imv_4star;
    @BindView(R.id.imv_5star)
    ImageView imv_5star;
    @BindView(R.id.imv_header)
    CircleImageView imv_header;
    @BindView(R.id.tv_publish_time)
    TextView tv_publish_time;

    private IPPTModel pptModel;
    private View.OnClickListener listener;
    private View bottom_view;
    private Dialog shareDialog;
    private LinearLayout layout_share_to_circle;
    private LinearLayout layout_share_to_friend;
    private LinearLayout layout_store;
    private LinearLayout layout_report;
    private LinearLayout layout_subscribe;
    private LinearLayout layout_delete;
    private CircleImageView ppt_share_store_imv;
    private CircleImageView ppt_share_subscribe_imv;
    private TextView tv_cancel;
    private LinearLayout layout_share_to_mail;
    private View input_email_view;
    private Dialog publish_ppt_dialog_url;
    private EditText edt_publish_url;
    private TextView tv_publish_url;
    private ImageView imv_close_dialog_publish;
    private TextView tv_dialog_title;

    @Override
    public int getLayoutId() {
        return R.layout.activity_ppt_webview;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        pptId = getIntent().getStringExtra("pptId");
        if (TextUtils.isEmpty(pptId)) {
            App.GetInstance().finishActivity(this);
        }
        listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
                    Intent intent = new Intent(PPTWebviewActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                int id = v.getId();
                switch (id) {
                    case R.id.imv_1star:
                        if (!entity.isLiked()) {
                            scorePPT(1);
                        }
                        break;
                    case R.id.imv_2star:
                        if (!entity.isLiked()) {
                            scorePPT(2);
                        }
                        break;
                    case R.id.imv_3star:
                        if (!entity.isLiked()) {
                            scorePPT(3);
                        }
                        break;
                    case R.id.imv_4star:
                        if (!entity.isLiked()) {
                            scorePPT(4);
                        }
                        break;
                    case R.id.imv_5star:
                        if (!entity.isLiked()) {
                            scorePPT(5);
                        }
                        break;
                }
            }
        };
        right_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
                    Intent intent = new Intent(PPTWebviewActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    shareDialog.show();
                }
            }
        });
        input_email_view = View.inflate(PPTWebviewActivity.this, R.layout.dialog_publish_ppt_url, null);
        initDialogViewsUrl();
        initPublishUrlDialog();
        pptModel = new PPTModelImpl();
//        requestPPTDetail();
    }


    private void initPublishUrlDialog() {
        publish_ppt_dialog_url = new Dialog(this, R.style.Theme_Light_Dialog);
        //获得dialog的window窗口
        Window window = publish_ppt_dialog_url.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(PPTWebviewActivity.this, 40);
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        publish_ppt_dialog_url.setCancelable(false);
        publish_ppt_dialog_url.setContentView(input_email_view);
    }

    private void initDialogViewsUrl() {
        edt_publish_url = (EditText) input_email_view.findViewById(R.id.edt_publish_url);
        edt_publish_url.setHint("输入邮箱地址");
        tv_publish_url = (TextView) input_email_view.findViewById(R.id.tv_publish_url);
        imv_close_dialog_publish = (ImageView) input_email_view.findViewById(R.id.imv_close_dialog_publish);
        tv_dialog_title=(TextView)input_email_view.findViewById(R.id.tv_dialog_title);
        tv_dialog_title.setText("输入邮箱");
        imv_close_dialog_publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edt_publish_url.setText("");
                publish_ppt_dialog_url.dismiss();
            }
        });
        tv_publish_url.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edt_publish_url.getText().toString())) {
                    ToastUtils.showShortToast(PPTWebviewActivity.this, R.string.ppt_string_55);
                    return;
                }
                if (!TextUtils.isEmpty(edt_publish_url.getText().toString())) {
                    if ((!edt_publish_url.getText().toString().contains("@"))) {
                        ToastUtils.showShortToast(PPTWebviewActivity.this, R.string.ppt_string_56);
                        return;
                    }
                    publish_ppt_dialog_url.dismiss();
                    Intent data=new Intent(Intent.ACTION_SENDTO);
                    data.setData(Uri.parse("mailto:"+edt_publish_url.getText().toString()));
                    data.putExtra(Intent.EXTRA_SUBJECT, entity.getPptTitle());
                    data.putExtra(Intent.EXTRA_TEXT, entity.getPptUrl());
                    startActivity(data);
                }
            }
        });
    }


    private void initDialoigViews() {
        bottom_view = View.inflate(PPTWebviewActivity.this, R.layout.dailog_ppt_share, null);
        layout_share_to_circle = (LinearLayout) bottom_view.findViewById(R.id.layout_share_to_circle);
        layout_share_to_mail=(LinearLayout)bottom_view.findViewById(R.id.layout_share_to_mail);
        layout_share_to_friend = (LinearLayout) bottom_view.findViewById(R.id.layout_share_to_friend);
        layout_store = (LinearLayout) bottom_view.findViewById(R.id.layout_store);
        layout_report = (LinearLayout) bottom_view.findViewById(R.id.layout_report);
        layout_subscribe = (LinearLayout) bottom_view.findViewById(R.id.layout_subscribe);
        layout_delete = (LinearLayout) bottom_view.findViewById(R.id.layout_delete);
        ppt_share_store_imv = (CircleImageView) bottom_view.findViewById(R.id.ppt_share_store_imv);
        ppt_share_subscribe_imv = (CircleImageView) bottom_view.findViewById(R.id.ppt_share_subscribe_imv);
        tv_cancel = (TextView) bottom_view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareDialog.dismiss();
            }
        });
        layout_share_to_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToWechat(true);
                shareDialog.dismiss();
            }
        });
        layout_share_to_mail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(entity.getEmail())){
                    publish_ppt_dialog_url.show();
                }
                else{
                    Intent data=new Intent(Intent.ACTION_SENDTO);
                    data.setData(Uri.parse("mailto:"+entity.getEmail()));
                    data.putExtra(Intent.EXTRA_SUBJECT, entity.getPptTitle());
                    data.putExtra(Intent.EXTRA_TEXT, entity.getPptUrl());
                    startActivity(data);
                }
                shareDialog.dismiss();
            }
        });
        layout_share_to_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToWechat(false);
                shareDialog.dismiss();
            }
        });
        layout_store.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareDialog.dismiss();
                if (entity.isFaved()) {
                    starPPT(false);
                } else {
                    starPPT(true);
                }
            }
        });
        layout_report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareDialog.dismiss();
                reportPPT(entity.getPptId() + "");
            }
        });
        layout_subscribe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!entity.isSubscribed()) {
                    shareDialog.dismiss();
                    subscribePPT();
                }
            }
        });
        layout_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new MaterialDialog.Builder(PPTWebviewActivity.this).content(PPTWebviewActivity.this.getResources().getString(R.string.ppt_string_37)).positiveText(PPTWebviewActivity.this.getResources().getString(R.string.ppt_string_39)).negativeText(PPTWebviewActivity.this.getResources().getString(R.string.ppt_string_40)).onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        shareDialog.dismiss();
                        doDeletePPT(entity.getPptId() + "");
                    }
                }).show();

            }
        });

        if (entity.isFaved()) {
            ppt_share_store_imv.setImageResource(R.mipmap.ppt_stored);
        } else {
            ppt_share_store_imv.setImageResource(R.mipmap.ppt_share_like);
        }

        if (entity.isSubscribed()) {
            ppt_share_subscribe_imv.setImageResource(R.mipmap.subscribed);
        } else {
            ppt_share_subscribe_imv.setImageResource(R.mipmap.ppt_share_susbcribe);
        }

        if (!TextUtils.isEmpty(PreferenceUtils.GetUserId())) {
            if (entity.getFromUserId().equals(PreferenceUtils.GetUserId())) {
                layout_report.setVisibility(View.GONE);
                layout_subscribe.setVisibility(View.GONE);
                layout_delete.setVisibility(View.VISIBLE);
            } else {
                layout_report.setVisibility(View.VISIBLE);
                layout_subscribe.setVisibility(View.VISIBLE);
                layout_delete.setVisibility(View.GONE);
                if (TextUtils.isEmpty(entity.getFromUserId())) {
                    layout_subscribe.setVisibility(View.GONE);
                }
            }
        }
    }


    private void shareToWechat(boolean isTimeLine) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = entity.getPptUrl();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = entity.getPptTitle();
        msg.description = this.getResources().getString(R.string.ppt_string_36);
        Bitmap bmp = BitmapFactory.decodeResource(App.GetInstance().getResources(), R.mipmap.app_icon);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true);
        bmp.recycle();
        msg.thumbData = FileUtils.bmpToByteArray(thumbBmp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "share_ppt";
        req.message = msg;
        if (isTimeLine) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        }
        WXAPIFactory.createWXAPI(App.GetInstance(), Constants.WEIXIN_APPID).sendReq(req);
    }

    private void initShareDialog() {
        shareDialog = new Dialog(this, R.style.Theme_Light_Dialog);
        //获得dialog的window窗口
        Window window = shareDialog.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = DisplayUtil.GetDisplayWidth();
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        shareDialog.setCancelable(false);
        shareDialog.setContentView(bottom_view);
    }

    @Override
    public void setupData() {
        WebSettings webSettings = scrollWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(true);
    }

    private void clearScores() {
        imv_1star.setImageResource(R.mipmap.rating_no1);
        imv_2star.setImageResource(R.mipmap.rating_no1);
        imv_3star.setImageResource(R.mipmap.rating_no1);
        imv_4star.setImageResource(R.mipmap.rating_no1);
        imv_5star.setImageResource(R.mipmap.rating_no1);
    }

    private void setAllEnable(boolean enable) {
        imv_1star.setEnabled(enable);
        imv_2star.setEnabled(enable);
        imv_3star.setEnabled(enable);
        imv_4star.setEnabled(enable);
        imv_5star.setEnabled(enable);
    }

    @OnClick({R.id.back_layout})
    void doClicks(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.back_layout:
                App.GetInstance().finishActivity(PPTWebviewActivity.this);
                break;
        }
    }

    private void scorePPT(final int score) {
        pptModel.LikePPTPoint(score, entity.getPptId()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<ScorePPT>() {
            @Override
            public void onSuccess(ScorePPT response) {
                hideProgress();
                entity.setPoint(response.getPoint());
                entity.setMyLikePoint(score);
                entity.setLikeAlready("y");
                initViews();
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(PPTWebviewActivity.this, response.getDesc());
            }
        });
    }

    private void starPPT(final boolean star) {

        pptModel.FavPPT(entity.getPptId(), star).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                hideProgress();
                if (star) {
                    entity.setFavAlready("y");
                } else {
                    entity.setFavAlready("n");
                }
                initViews();
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(PPTWebviewActivity.this, response.getDesc());
            }
        });
    }

    private void doDeletePPT(String pptId) {
        pptModel.DeletePPT(pptId).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                hideProgress();
                App.GetInstance().finishActivity(PPTWebviewActivity.this);
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(PPTWebviewActivity.this, response.getDesc());
            }
        });
    }

    private void subscribePPT() {
        pptModel.SubscribePPT(entity.getFromUserId()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                hideProgress();
                entity.setSubscribeUserAlready("y");
                initViews();
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(PPTWebviewActivity.this, response.getDesc());
            }
        });
    }

    private void reportPPT(String pptId) {
        pptModel.ReportPPT(pptId).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(PPTWebviewActivity.this, getResources().getString(R.string.ppt_string_38));
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(PPTWebviewActivity.this, response.getDesc());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestPPTDetail();
    }

    private void requestPPTDetail() {
        pptModel.QueryPPTDetail(pptId).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<PPTDetailBean>() {
            @Override
            public void onSuccess(PPTDetailBean response) {
                entity = response.getDataList().get(0);
                entity.setEmail(response.getEmail());
                scrollWebview.loadUrl(entity.getPptUrl());
                initViews();
                hideProgress();
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.showShortToast(PPTWebviewActivity.this, response.getDesc());
                hideProgress();
            }
        });
    }

    private void initViews() {
        tv_title.setText("PPTShare");
        clearScores();
        if (!TextUtils.isEmpty(entity.getFromUserId())) {
                initDialoigViews();
                initShareDialog();
        }
        imv_1star.setOnClickListener(listener);
        imv_2star.setOnClickListener(listener);
        imv_3star.setOnClickListener(listener);
        imv_4star.setOnClickListener(listener);
        imv_5star.setOnClickListener(listener);
        if ((!TextUtils.isEmpty(PreferenceUtils.GetUserToken())) && (entity.isLiked())) {
            if (entity.getMyLikePoint() >= 1) {
                imv_1star.setImageResource(R.mipmap.rating_yes1);
            }
            if (entity.getMyLikePoint() >= 2) {
                imv_2star.setImageResource(R.mipmap.rating_yes1);
            }
            if (entity.getMyLikePoint() >= 3) {
                imv_3star.setImageResource(R.mipmap.rating_yes1);
            }
            if (entity.getMyLikePoint() >= 4) {
                imv_4star.setImageResource(R.mipmap.rating_yes1);
            }
            if (entity.getMyLikePoint() >= 5) {
                imv_5star.setImageResource(R.mipmap.rating_yes1);
            }
            setAllEnable(false);
        } else {
            clearScores();
            setAllEnable(true);
        }
        tv_ppt_name.setText(entity.getPptTitle());
        GlideUtils.getInstance().LoadContextBitmap(this, Constants.BASE_URL + entity.getHeadImgUrl(), imv_header, R.mipmap.default_comment_header, R.mipmap.default_comment_header, GlideUtils.LOAD_BITMAP);
        tv_ppt_author.setText("上传人: "+entity.getFromUserName());
        tv_publish_time.setText(TimeUtils.formatTime(entity.getCreateTime()));
    }
}

